<script setup lang="ts">
import { ElNotification } from "element-plus";
import { ref, onMounted, defineProps, computed } from "vue";
import {
  try_get_all_records,
  try_get_user_records,
  BorrowRecord,
  try_return_book,
  try_delete_records,
} from "./book";

const props = defineProps({
  user: {
    required: true,
  },
});
const records = ref<BorrowRecord[]>([]);

const get_all_records = async () => {
  try {
    records.value = await try_get_all_records();
  } catch (error) {
    ElNotification.error({
      message: "获取所有借阅记录失败!\n" + error,
      title: "Error",
      duration: 10000,
    });
  }
};

const get_user_records = async (uid: number) => {
  try {
    records.value = await try_get_user_records(uid);
  } catch (error) {
    ElNotification.error({
      message: "获取用户借阅记录失败!\n" + error,
      title: "Error",
      duration: 10000,
    });
  }
};
const is_loading = ref(false);
const refresh = async () => {
  is_loading.value = true;
  if (props.user == "super") {
    await get_all_records();
  } else {
    //@ts-ignore
    const uid = parseInt(props.user);
    if (Number.isInteger(uid) && uid > 0) {
      await get_user_records(uid);
    } else {
      ElNotification.error({
        message: "用户ID无效:" + props.user,
        title: "Error",
        duration: 10000,
      });
    }
  }
  is_loading.value = false;
};

onMounted(async () => {
  await refresh();
});

const filter_word = ref("");
type order_fields = keyof BorrowRecord;
type desc = true | false;
type order = [order_fields, desc];
const order_type = ref<order>(["borrowDate", true]);

const filtered_records = computed(() => {
  if (filter_word.value) {
    return records.value.filter((r) => r.bookName.includes(filter_word.value));
  } else {
    return records.value;
  }
});

const ordered_records = computed(() => {
  return filtered_records.value.sort((r1, r2) => {
    const res: number = r1[order_type.value![0]] > r2[order_type.value![0]] ? 1 : -1;
    return order_type.value![1] ? -res : res;
  });
});

const return_book = async (row: BorrowRecord) => {
  try {
    const record = await try_return_book(row.id);
    ElNotification.success({
      message: "归还书籍成功!",
      title: "Success",
      duration: 5000,
    });
    row.returnDate = record.returnDate;
  } catch (error) {
    ElNotification.error({
      message: "归还书籍失败!\n" + error,
      title: "Error",
      duration: 10000,
    });
  }
};
const book_name_filter = (value: string, row: BorrowRecord, column: any) => {
  if (!filter_word.value) {
    return true;
  }
  return value.includes(filter_word.value);
};
const delete_record=async (row:BorrowRecord)=>{
    try {
        await try_delete_records(row.id)
        ElNotification.success({
            message:'删除记录成功!',
            title:'Success',
            duration:5000,
        })
        const idx=records.value.findIndex(br=>br.id==row.id)
        records.value.splice(idx,1)
    } catch (error) {
        ElNotification.error({
            message:'删除记录失败!\n'+error,
            title:'Error',
            duration:10000,
        })
    }
}
</script>


<template>
  <div class="w-full h-full flex flex-col justify-center items-center gap-4">
    <div class="w-full flex justify-center items-center gap-4">
      <el-input
        v-model="filter_word"
        class="w-[200px]"
        placeholder="书名检索"
        clearable
      ></el-input>
      <el-button type="primary" @click="refresh()">刷新</el-button>
    </div>
    <el-table
      v-loading="is_loading"
      stripe
      :data="records"
      height="600px"
      class="shadow-lg"
      style="max-width: 90%"
      :filter-method="book_name_filter"
    >
      <el-table-column type="index" width="60" label="No" />
      <el-table-column
        v-if="user == 'super'"
        prop="userName"
        label="用户"
        width="100"
      ></el-table-column>
      <el-table-column prop="bookName" label="书名" sortable></el-table-column>
      <el-table-column prop="borrowDate" label="借阅日期" width="160" sortable></el-table-column>
      <el-table-column prop="returnDate" label="归还日期" width="160" sortable></el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag type="danger" v-if="!scope.row.returnDate">借阅中</el-tag>
          <el-tag type="success" v-else>已归还 </el-tag>
        </template>
      </el-table-column>
      <el-table-column width="100" v-if="user=='super'">
        <template #default="scope">
          <el-popconfirm
            title="确认删除?"
            @confirm="delete_record(scope.row)"
          >
            <template #reference>
              <el-button type="danger" 
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column width="100" v-else>
        <template #default="scope">
          <el-popconfirm
            title="确认归还?"
            v-if="!scope.row.returnDate"
            @confirm="return_book(scope.row)"
          >
            <template #reference>
              <el-button type="primary" :disabled="!!scope.row.returnDate"
                >归还</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped></style>
